package com.example.pictureManage.controller;

import com.example.pictureManage.FileNode;
import com.example.pictureManage.service.mainViewService.fileService;
import com.example.pictureManage.service.mainViewStage;
import com.example.pictureManage.util.FileUtil;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.TilePane;
import javafx.scene.layout.VBox;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import com.example.pictureManage.util.FileUtil;

import static com.example.pictureManage.service.mainViewStage.reload;

/**
 * @author 关于主窗口的Controller
 */
public class MainViewController {

    //关于file 的服务层 因为二者有互相依赖的情况所以要规定ImageService先实例化
    private final fileService fileServer = new fileService();

    //关于选中图片信息的标签显示
    @FXML
    private Label fileDetail;

    @FXML
    private TreeView<String> directoryTree;
    //目录树

    @FXML
    private TilePane contentPane;
    //显示图片的地方

    @FXML
    private VBox outtree;

    @FXML
    private void initialize() {
        // 获取所有磁盘根路径
        File[] roots = File.listRoots();

        // 创建根节点
        FileNode rootItem = new FileNode("计算机",Path.of(""));
        rootItem.setExpanded(true);

        // 遍历所有磁盘根路径并添加到树中
        for (File root : roots) {
            FileNode rootItemNode = new FileNode(root.getAbsolutePath(), Path.of(root.getAbsolutePath()));
            rootItem.getChildren().add(rootItemNode);
            pushTreeView(root,rootItemNode);
        }

        // 设置 TreeView 的根节点
        directoryTree.setRoot(rootItem);

        directoryTree.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
            FileNode selectedItem = (FileNode) directoryTree.getSelectionModel().getSelectedItem();

            if (selectedItem != null && Files.isReadable(selectedItem.getFilePath()) && !selectedItem.getValue().equals("$Recycle.Bin")) {
                if (selectedItem.getChildren().isEmpty()) {
                    // 如果当前节点没有子节点，则调用 pushTreeView 方法加载子节点
                    pushTreeView(new File(String.valueOf(selectedItem.getFilePath())), selectedItem);
                }
                if (event.getClickCount() > 1) {
//                    FileUtil.fillTree(selectedItem.getFilePath(), selectedItem);
                    mainViewStage.displaySelectedFolder(selectedItem,contentPane,fileDetail);
//                    mainViewStage.reload();
                }
            }
        });
        
        //添加更改目录 监听器事件
        directoryTree.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            //空的直接返回就行
            if (newValue == null){
                return;
            }
            //祖父节点
            FileNode parentNode = (FileNode) newValue;
            //父亲节点
            ObservableList<TreeItem<String>> children = parentNode.getChildren();
            for (TreeItem<String> child : children) {
                FileUtil.loadDir((FileNode) child);
            }

        });

        outtree.setMaxWidth(400);
    }

    private void pushTreeView(File directory, TreeItem<String> parentItem) {
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {

                    StringBuilder re = new StringBuilder();
                    re.append(file.getPath());
                    re.reverse();
                    while(re.indexOf(String.valueOf('\\')) >= 0) {
                        re.deleteCharAt(re.length() - 1);
                    }
                    re.reverse();
                    String fileName = re.toString();

                    FileNode dirItem = new FileNode(fileName, Path.of(file.getPath()));
                    System.out.println(fileName);

                    if(!fileName.equals("$Recycle.Bin")) {
                        parentItem.getChildren().add(dirItem);
                    }
                }
            }
        }
    }



    @FXML
    private void handleBackToPreview() {
        contentPane.getChildren().clear();
        mainViewStage.displaySelectedFolder((FileNode) directoryTree.getSelectionModel().getSelectedItem(),contentPane,fileDetail);
    }

    @FXML
    private void handlePlay(){
        try {
            //获取预览区域第一个图片
            ObservableList<Node> nodes = contentPane.getChildren();
            Node nodesFirst = nodes.getFirst();
            Image image = new Image((String) nodesFirst.getUserData());

            //初始化环境
            Stage imageStage = new Stage();
            URL url = getClass().getResource("/com/example/pictureManage/image-detail-view.fxml");
            FXMLLoader loader = new FXMLLoader(url);
            VBox root = loader.load();

            ImageDetailController controller = loader.getController();
            //提前准备好stage
            imageStage.setScene(new Scene(root));

            //设置标题
            Path path = Paths.get(URI.create(image.getUrl()));
            imageStage.setTitle(FileUtil.getFileName(path));
            imageStage.show();
            controller.initialize(image, imageStage);

            controller.handlePlay();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}